import Taro, { useEffect } from '@tarojs/taro';
import { View, Text } from '@tarojs/components';
import { AtButton } from 'taro-ui';
import { connect } from '@tarojs/redux';
import './index.scss';

const Authlogin = props => {
  const { authLogin, loading, dispatch } = props;
  // componentDidMount
  useEffect(() => {
    console.log(props)
  }, [])
  // componentWillUnmount
  useEffect(() => {
    return () => {
      console.log(props)
    }
  }, [])

  const setLoading = (loading) => {
    dispatch({
      type: 'authLogin/setData',
      payload: {
        loading: loading
      }
    })
  }

  const tobegin = (res) => {
    console.log(res)
    if (res.detail.userInfo) { // 返回的信息中包含用户信息则证明用户允许获取信息授权
      console.log('授权成功')
      // 保存用户信息微信登录
      Taro.setStorageSync('userInfo', res.detail.userInfo)

      setLoading(!authLogin.loading)
      Taro.login({
        success: function (resLogin) {
          const accountInfo = Taro.getAccountInfoSync();

          const appId = accountInfo.miniProgram.appId // 小程序 appId
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          if (resLogin.code) {
            dispatch({
              type: 'authLogin/login', payload: {
                ...res.detail, nickName: res.detail.userInfo.nickName, code: resLogin.code, appId: appId
              }
            })
          }
          setLoading(false)
        }
      })
    }
    //  else {
    //   Taro.switchTab({ url: '/pages/book/index' })
    // }
  }
  return (
    <View className="index-page" style="height:100vh">
      <View className='textAlign need'>需要使用你的微信昵称和头像</View>
      <AtButton
        className='at-col defaultWidth button'
        loading={authLogin.loading}
        openType='getPhoneNumber'
        onGetPhoneNumber={tobegin}
      >
        点击授权
      </AtButton>
      <AtButton
        type='secondary'
        className='at-col defaultWidth'
        onClick={() => Taro.switchTab({ url: '/pages/book/index' })}
      >
        暂不登录
      </AtButton>
    </View>
  )
}
Authlogin.config = {
  navigationBarTitleText: '授权登录'
}
//全局样式继承 你可以关掉
Authlogin.options = {
  addGlobalClass: true
}

const mapStateToProps = ({ loading, authLogin }) => {
  return {
    loading,
    authLogin,
  };
};

export default connect(mapStateToProps)(Authlogin)
